package comsvc

import (
	"context"
	"fmt"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"time"
)

func GetAppInfo(appId string) (*model.TbApplication, error) {
	var err error
	app := new(model.TbApplication)
	key := fmt.Sprintf("app:%s", appId)
	rds := sdk.Redis(context.Background())
	val := rds.Get(key).Val()
	if val == "" {
		db := sdk.DB(context.Background())
		err = db.First(app, "app_id = ?", appId).Error
		if err != nil {
			return nil, err
		}
		str, _ := utils.JsonMarshal(app)
		rds.Set(key, string(str), time.Hour*24)
	} else {
		err = utils.JsonUnmarshal([]byte(val), app)
		if err != nil {
			return nil, err
		}
	}
	return app, nil
}

func CacheFirebaseDeviceToken(appId string, uid string, token string) {
	key := fmt.Sprintf("fdt:%v:%v", appId, uid)
	rds := sdk.Redis(context.Background())
	//缓存用户的设备deviceToken90天
	rds.Set(key, token, time.Hour*2160)
}

func GetFirebaseDeviceToken(appId string, uid string) string {
	key := fmt.Sprintf("fdt:%v:%v", appId, uid)
	rds := sdk.Redis(context.Background())
	val := rds.Get(key).Val()
	return val
}
